package com.yx.gifts;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Build;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.yx.gifts.adapter.GiftGridAdapter;
import com.yx.gifts.adapter.GiftRecyclerAdapter;
import com.yx.gifts.adapter.GiftViewPagerAdapter;
import com.yx.gifts.adapter.GridSpacingItemDecoration;
import com.yx.gifts.bean.Gift;
import com.yx.gifts.customer.ContentViewPager;
import com.yx.gifts.customer.DpPxUtils;
import com.yx.gifts.customer.SendGiftView;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * Created : Yx
 * Time : 2018/11/27 15:21
 * Describe :送礼物
 */
public class DialogGift {
    private static Dialog dialog;
    private static int ori;//当前屏幕方向
    public static String[] mTitles;//导航分类类别 mTitles= {"礼物1", "礼物2", "礼物3"}
    public static List<List<Gift>> dataList;//导航类别对应的礼物列表dataList = new ArrayList<>()
    //礼物视图
    private static List<View> pageViewList = new ArrayList<View>();//一个类别中的礼物分页视图
    private static GiftViewPagerAdapter gAdapter;//分页ViewPager

    private static LinearLayout dotll;//底部小点父布局
    private static ImageView[] dots;// 底部小点图片
    private static int currentIndex;// 记录当前Viewpage/dot选中位置

    private static int radioIndex;//当前点击的导航下标
    private static String inBalance;//查询到当前我的余额

    private static String liveId;//直播间ID
    //当前选择的礼物信息
    private static Gift gift;//当前选择了？礼物
    private static BigDecimal liwuPrice;//礼物价格
    private static ArrayList<Gift> gifts = new ArrayList<>();//送过的礼物类型集合
    private static TextView tv_send;//发送礼物按钮

    /**
     * 送送送送礼物
     *
     * @param mContext
     */
    public static void showGift(Context mContext, String liveIds, SendGiftView sendGiftView) {
        //mTitles = mTitlesData;
        //dataList = datas;
        liveId = liveIds;
        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_gift, null);
        dialog = new AlertDialog.Builder(mContext, R.style.TranslucentNoBar).show();

        dialog.setCanceledOnTouchOutside(true);
        dialog.setContentView(view);

        Window window = dialog.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.MATCH_PARENT;
        window.setAttributes(lp);
        window.setWindowAnimations(R.style.dialog_animation1);  //添加动画
        setTranslucentStatus(mContext, dialog);
        //视图控件处理
        RelativeLayout main_ll = view.findViewById(R.id.gift_main_rl);
        main_ll.setOnClickListener(v -> hidn());
        RelativeLayout send_rl = view.findViewById(R.id.gift_send_rl);
        send_rl.setOnClickListener(v -> Log.i("aaaa", "啥也不干"));//为了防止点击到该Rl布局导致hind的问题
        RadioGroup rgChannel = view.findViewById(R.id.f_rg);//导航
        ContentViewPager mViewPager = view.findViewById(R.id.f_vpg);//竖屏数据view
        RecyclerView mRecyclerView = view.findViewById(R.id.gift_rv);//横屏数据view
        GridSpacingItemDecoration decoration = new GridSpacingItemDecoration(1, DpPxUtils.dip2px(mContext, 5), true);//columnsComment列间距为10dp,true代表有边界，false代表无边界
        mRecyclerView.addItemDecoration(decoration);//分割间距
        dotll = view.findViewById(R.id.dian_ll);//底部小点父布局
        TextView yu_e = view.findViewById(R.id.gift_yu_e);//余额，剩余
        tv_send = view.findViewById(R.id.gift_tv_send);//发送礼物
        try {
            //礼物展示适配
            initData(mContext, rgChannel, mViewPager, mRecyclerView);
        } catch (Exception e) {
            Log.i("aaaa", "--DialogGift程序异常--" + e.toString() + e.getMessage());
        }

        //查询我的余额,并设置
        inBalance = "99999999";//测试金额
        yu_e.setText(inBalance + "");
        //Send发送礼物
        tv_send.setOnClickListener(v -> {
            //if (NoDoubleClickUtil.isFastClick()) {
            //    return;
            //}
            if (inBalance != null && gift != null && gift.getId() > 0) {
                BigDecimal yu_er = new BigDecimal(inBalance);
                if (yu_er.compareTo(liwuPrice) >= 0) {//余额充足或刚好
                    //展示礼物动画
                    if (!gifts.contains(gift)) {
                        gifts.add(gift);
                        sendGiftView.setGift(gift);//设置人物礼物数据
                    }
                    sendGiftView.addNum(1);//展示的礼物数量

                    //动画监听
                    sendGiftView.setOnAnimatorListener(null);
                    //调用送出礼物接口，送出成功更新余额
                    //当前余额
                    BigDecimal aMoney = yu_er.subtract(liwuPrice).setScale(2, BigDecimal.ROUND_HALF_DOWN);
                    Log.i("aaaa", "---送完后剩余---" + aMoney.toString());
                    yu_e.setText(aMoney.toString());

                } else {
                    //余额不足，没钱了
                    Toast.makeText(mContext, "余额不足", Toast.LENGTH_LONG).show();
                }

            }
        });
    }

    public static void hidn() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
            dialog.cancel();
            dialog = null;
            pageViewList.clear();
            gift = null;
            tv_send = null;
            gifts.clear();
            dots = null;
            ori = 0;
        }
    }

    private static void initData(Context mContext, RadioGroup rgChannel, ContentViewPager mViewPager, RecyclerView mRecyclerView) {
        //数据处理
        if (mTitles != null && mTitles.length > 0) {
            //Tab导航控件
            for (int i = 0; i < mTitles.length; i++) {
                RadioButton rb = (RadioButton) LayoutInflater.from(
                        mContext).inflate(R.layout.tab_mygift, null);
                rb.setId(i);
                rb.setText(mTitles[i]);
                RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(
                        RadioGroup.LayoutParams.WRAP_CONTENT,
                        RadioGroup.LayoutParams.MATCH_PARENT);
                rgChannel.addView(rb, params);//为radiogrup添加rb
                //DpPxUtils.dip2px(mContext, 80)
            }


            Configuration mConfiguration = mContext.getResources().getConfiguration(); //获取设置的配置信息
            ori = mConfiguration.orientation; //获取屏幕方向
            if (ori == mConfiguration.ORIENTATION_PORTRAIT) {//当前屏幕方向竖屏
                //竖屏
                mRecyclerView.setVisibility(View.GONE);//横向控件隐藏
                mViewPager.setVisibility(View.VISIBLE);//竖向控件显示
                dotll.setVisibility(View.VISIBLE);//底部小点父布局显示
            } else if (ori == mConfiguration.ORIENTATION_LANDSCAPE) {//当前屏幕方向横屏
                //横屏
                mViewPager.setVisibility(View.GONE);//竖向控件隐藏
                dotll.setVisibility(View.GONE);//底部小点父布局隐藏
                mRecyclerView.setVisibility(View.VISIBLE);//横向控件显示
            }

            // Tab点击事件监听,点击tab同时切换viewpager
            rgChannel.setOnCheckedChangeListener((group, checkedId) -> {
                RadioButton rbButton = (RadioButton) rgChannel.getChildAt(radioIndex);//上一次点击的背景恢复
                rbButton.setBackgroundColor(ContextCompat.getColor(mContext, R.color.transparent));
                int radioButtonId = group.getCheckedRadioButtonId();//点击下标
                radioIndex = radioButtonId;
                //mViewPager.setCurrentItem(checkedId);
                RadioButton rbButton2 = (RadioButton) rgChannel.getChildAt(radioButtonId);//当前点击的背景设置
                rbButton2.setBackgroundColor(ContextCompat.getColor(mContext, R.color.color_00C47A));
                if (ori == mConfiguration.ORIENTATION_PORTRAIT) {//当前屏幕方向竖屏
                    //竖屏
                    initGiftVertical(mContext, radioButtonId, mViewPager);
                } else if (ori == mConfiguration.ORIENTATION_LANDSCAPE) {//当前屏幕方向横屏
                    //横屏
                    initGiftHorizontal(mContext, radioButtonId, mRecyclerView);
                }

            });//添加tab点击监听

            //默认选中0号tab
            setTab(rgChannel, 0);
        }
    }

    //=======================竖屏下对应===========================
    private static void initGiftVertical(Context mContext, int index, ContentViewPager mViewPager) {//index点击的导航类别下标
        if (pageViewList != null && pageViewList.size() > 0) {
            pageViewList.clear();
            dotll.removeAllViews();//清空布局
        }
        if (dataList == null) return;
        List<Gift> sl = dataList.get(index);//该导航类别下对应的所有礼物
        List<List<Gift>> spData = splitList(sl, 10);//如：该导航类别下对应有100个礼物，按每10个一组分成10份
        if (spData == null) {
            //该导航类别下无礼物，则添加空视图
            spData = new ArrayList<>();
            List<Gift> list = new ArrayList<>();
            spData.add(list);
        }
        for (int i = 0; i < spData.size(); i++) {
            //设置第i组礼物
            View views = LayoutInflater.from(mContext).inflate(R.layout.dialog_gift_views, null);
            GridView gridView = (GridView) views.findViewById(R.id.gift_gvone);
            gridView.setNumColumns(5);
            GiftGridAdapter adapter = new GiftGridAdapter(mContext, spData.get(i));
            gridView.setAdapter(adapter);
            gridView.setOnItemClickListener((parent, view, position, id) -> {
                //选中了该[页面]下的该礼物
                adapter.selectItem(position);
                gift = adapter.getDataList().get(position);
                tv_send.setBackground(ContextCompat.getDrawable(mContext, R.drawable.bg_blue_radius5dp));
                liwuPrice = new BigDecimal(adapter.getDataList().get(position).getGold());
            });
            pageViewList.add(views);//放入布局

            //每组礼物，添加对应的小点
            ImageView imageView = new ImageView(mContext);
            imageView.setBackgroundResource(R.drawable.dot_circle);
            imageView.setPadding(4, 4, 4, 4);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            params.gravity = Gravity.CENTER;  //必须要加上这句，setMargins才会起作用，而且此句还必须在setMargins下面
            imageView.setLayoutParams(params);
            dotll.addView(imageView);
        }
        gAdapter = new GiftViewPagerAdapter(pageViewList);
        mViewPager.setAdapter(gAdapter);//将布局集合放到ViewPagerz中
        //底部小点适配
        initDots(spData.size());

        // 页面改变监听，手指滑动翻页触发
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                // 设置底部小点选中状态
                //Log.i("aaaa", "======positon-is:=====" + positon);
                if (position < 0 || position > pageViewList.size() - 1 || currentIndex == position) {
                    return;
                }
                //Log.i("aaaa", "=======selected========" + positon);
                dots[position].setEnabled(false);
                dots[currentIndex].setEnabled(true);
                currentIndex = position;
                //更新除当前选择的礼物页的其他礼物页(该代码防止在每页下都有选中某礼物,不太好看问题)
                // 由于刷新视图过于频繁，先不使用，等人家反馈了在打开
                //for (int i = 0; i < pageViewList.size(); i++) {
                //    if (i != position) {
                //        GridView gridView = (GridView) pageViewList.get(i).findViewById(R.id.gift_gvone);
                //        GiftGridAdapter adapter = (GiftGridAdapter) gridView.getAdapter();
                //        adapter.selectItem(-1);
                //    }
                //}
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });


    }

    //=======================横屏下对应===========================
    private static void initGiftHorizontal(Context mContext, int index, RecyclerView mRecyclerView) {
        if (dataList == null) return;
        List<Gift> sl = dataList.get(index);//该导航类别下对应的所有礼物
        //创建LinearLayoutManager
        LinearLayoutManager manager = new LinearLayoutManager(mContext);
        //设置为横向滑动
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        //设置
        mRecyclerView.setLayoutManager(manager);
        //实例化适配器
        GiftRecyclerAdapter myAdapter = new GiftRecyclerAdapter(mContext, sl);
        myAdapter.setOnRecyclerViewListener(new GiftRecyclerAdapter.OnRecyclerViewListener() {
            @Override
            public void onItemClick(int position) {
                //选中了该[导航]类目下的该礼物
                myAdapter.selectItem(position);
                gift = myAdapter.getDataList().get(position);
                tv_send.setBackground(ContextCompat.getDrawable(mContext, R.drawable.bg_blue_radius5dp));
                liwuPrice = new BigDecimal(myAdapter.getDataList().get(position).getGold());
            }

            @Override
            public boolean onItemLongClick(int position) {
                return false;
            }
        });
        //设置适配器
        mRecyclerView.setAdapter(myAdapter);
    }

    /**
     * 推荐话题底部小点
     */
    private static void initDots(int num) {
        dots = new ImageView[num];// 底部小点等于图片数的长度（4）
        // 循环取得小点图片
        for (int i = 0; i < num; i++) {
            dots[i] = (ImageView) dotll.getChildAt(i);// 获得第i个点点图片
            dots[i].setVisibility(View.VISIBLE);
            dots[i].setEnabled(true);// 都设为灰色
            //dots[i].setOnClickListener(this);// 设置点点的点击事件，需要implements-OnClickListener
            dots[i].setTag(i);// 设置位置tag，方便取出与当前位置对应
        }

        currentIndex = 0;// 当前选中位置0
        dots[currentIndex].setEnabled(false);// 设置为黑色，即选中状态
    }

    /***
     * 选中某个RadioButton
     * @param id
     */
    private static void setTab(RadioGroup rgChannel, int id) {
        RadioButton rbButton = (RadioButton) rgChannel.getChildAt(id);
        //设置标题被点击
        rbButton.setChecked(true);
    }

    //================================虚拟导航↓========================================
    public static void setTranslucentStatus(Context mContext, Dialog dialog) {
        Window window = dialog.getWindow();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//大于等于5.0
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);// 透明状态栏
            if (checkDeviceHasNavigationBar(mContext)) {
                //有虚拟导航栏
                setToNavigationBarTOP(window);//让弹出dialog在导航栏之上
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);//透明的状态栏和导航栏，必须API Level >= 21/5.0使用
                window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);// SDK21 清理状态栏半透明背景
                window.setStatusBarColor(Color.TRANSPARENT);// SDK21 将状态栏背景设置为透明
            }
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {//7.0 通过反射改变灰色状态栏背景为透明
            try {
                Class decorViewClazz = Class.forName("com.android.internal.policy.DecorView");
                Field field = decorViewClazz.getDeclaredField("mSemiTransparentStatusBarColor");
                field.setAccessible(true);
                field.setInt(dialog.getWindow().getDecorView(), Color.TRANSPARENT);  //改为透明
            } catch (Exception e) {
            }


        }
    }

    /**
     * 获取是否存在虚拟导航栏NavigationBar
     * true 有  false 无
     */
    public static boolean checkDeviceHasNavigationBar(Context mContext) {
        boolean hasNavigationBar = false;
        Resources rs = mContext.getResources();
        int id = rs.getIdentifier("config_showNavigationBar", "bool", "android");
        if (id > 0) {
            hasNavigationBar = rs.getBoolean(id);
        }
        try {
            Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
            Method m = systemPropertiesClass.getMethod("get", String.class);
            String navBarOverride = (String) m.invoke(systemPropertiesClass, "qemu.hw.mainkeys");
            if ("1".equals(navBarOverride)) {
                hasNavigationBar = false;
            } else if ("0".equals(navBarOverride)) {
                hasNavigationBar = true;
            }
        } catch (Exception e) {
        }
        return hasNavigationBar;
    }

    /**
     * 设置Dialog在虚拟导航上面
     *
     * @param window
     */
    private static void setToNavigationBarTOP(Window window) {
        window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
        window.getDecorView().setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
            @Override
            public void onSystemUiVisibilityChange(int visibility) {
                int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
                        //布局位于状态栏下方
                        View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
                        //全屏
                        //View.SYSTEM_UI_FLAG_FULLSCREEN |
                        //隐藏导航栏
                        View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
                        View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
                if (Build.VERSION.SDK_INT >= 19) {
                    uiOptions |= 0x00001000;
                } else {
                    uiOptions |= View.SYSTEM_UI_FLAG_LOW_PROFILE;
                }
                window.getDecorView().setSystemUiVisibility(uiOptions);
            }
        });


    }

    /**
     * 按指定大小，分隔集合，将集合按规定个数分为n个部分
     * *
     *
     * @param list *
     * @param len  *
     * @return
     */
    public static List<List<Gift>> splitList(List<Gift> list, int len) {
        if (list == null || list.isEmpty() || len < 1) {
            return null;
        }
        List<List<Gift>> result = new ArrayList<>();
        int size = list.size();
        int count = (size + len - 1) / len;
        for (int i = 0; i < count; i++) {
            List<Gift> subList = list.subList(i * len, ((i + 1) * len > size ? size : len * (i + 1)));
            result.add(subList);
        }
        return result;
    }

}
